﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Infraestructure.CrossCutting.Mailing;
using System.Net.Mail;
using System.Text.RegularExpressions;

using Infraestructure.CrossCutting.NetFramework.Resources;

namespace Infraestructure.CrossCutting.NetFramework.Mailing
{
    public sealed class EmailManager 
        : IEmailManager
    {

        private const string strRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
                                  @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
                                  @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";

        private Regex re;

        public EmailManager()
        {
            re = new Regex(strRegex);
        }

        public bool Send(string to, string from, string subject, string body)
        {
            if (!re.IsMatch(to))
            {
                throw new ArgumentException("to", Messages.exception_InvalidEmail);
            }

            if (!re.IsMatch(from))
            {
                throw new ArgumentException("from", Messages.exception_InvalidEmail);
            }

            MailMessage msg = new MailMessage();

            msg.To.Add(new MailAddress(to));
            msg.From = new MailAddress(from);
            msg.Subject = subject;
            msg.Body = body;
            SmtpClient clienteSmtp = new SmtpClient();
            try
            {
                clienteSmtp.Send(msg);
                return true;
            }
            catch
            {
                return false;
            }
        }

        public bool Send(string[] to, string from, string subject, string body)
        {
            foreach (string item in to)
            {
                if (!re.IsMatch(item))
                {
                    throw new ArgumentException("to: " + item, Messages.exception_InvalidEmail);
                }
            }

            if (!re.IsMatch(from))
            {
                throw new ArgumentException("from", Messages.exception_InvalidEmail);
            }

            MailMessage msg = new MailMessage();

            foreach (string item in to)
            {
                msg.To.Add(new MailAddress(item));
            }

            msg.From = new MailAddress(from);
            msg.Subject = subject;
            msg.Body = body;
            SmtpClient clienteSmtp = new SmtpClient();
            try
            {
                clienteSmtp.Send(msg);
                return true;
            }
            catch
            {
                return false;
            }
        }

        public bool ValidateEmailAddress(string email)
        {
            return re.IsMatch(email);
        }
    }
}
